package com.qs.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Session;

import com.infomanage.bean.FieldBean;
import com.infomanage.bean.SearchBean;
import com.infomanage.dao.BaseDAO;
import com.infomanage.exception.DaoException;
import com.infomanage.po.Department;
import com.infomanage.po.HibernateSessionFactory;
import com.infomanage.po.Person;
import com.jiuqi.webtree.util.StringUtils;
import com.qs.po.QsCtMmoTest;
import com.qs.vo.IndividualAnalResultItem;
import com.qs.vo.QsCtMmoTestItem;

public class QsCtMmoTestDAO extends BaseDAO<QsCtMmoTest> {

	private static final String[] JOIN_FIELDS = new String[] { "personId",
			"personId", "personId", "deptId" };
	private static final String[] MASTER_FIELDS = new String[] { "trainee",
			"zdLeader", "ddLeader", "deptId" };

	@SuppressWarnings("unchecked")
	public QsCtMmoTestItem find(int id) throws DaoException {
		try {
			SearchBean searchBean = new SearchBean();
			FieldBean fieldBean = new FieldBean();
			fieldBean.setName("id");
			fieldBean.setValue(id);
			searchBean.add(fieldBean);
			List result = super.findByFields(new Class[] { Person.class,
					Person.class, Person.class, Department.class },
					QsCtMmoTest.class, JOIN_FIELDS, MASTER_FIELDS, searchBean);
			List<QsCtMmoTestItem> items = parseResult(result);
			return items.size() == 0 ? null : items.get(0);
		} catch (Exception e) {
			throw new DaoException(e);
		} finally {
			HibernateSessionFactory.closeSession();
		}
	}

	@SuppressWarnings("unchecked")
	public List<QsCtMmoTestItem> findAll() throws DaoException {
		try {
			List result = findAllMutilTable(new Class[] { Person.class,
					Person.class, Person.class, Department.class },
					QsCtMmoTest.class, JOIN_FIELDS,
					MASTER_FIELDS);
			return parseResult(result);
		} catch (Exception e) {
			throw new DaoException(e);
		} finally {
			HibernateSessionFactory.closeSession();
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<QsCtMmoTestItem> findByFields(SearchBean searchBean)
			throws DaoException {
		List result = super.findByFields(new Class[] { Person.class,
				Person.class, Person.class, Department.class },
				QsCtMmoTest.class, JOIN_FIELDS, MASTER_FIELDS, searchBean);
		return parseResult(result);
	}
	
	public List<IndividualAnalResultItem> findByTraineeAndDate(String[] traineeIds,
			String beginDate, String endDate) throws DaoException {
		if(traineeIds == null || traineeIds.length == 0) {
			return null;
		}
		String hsql = "select T1.TRAINEE,T2.name,T1.TIMESTAMP,T1.FINAL_SCORE from qs_ct_mmo_test"
				+ " as T1 inner join person"
				+ " as T2 on T1.TRAINEE = T2.person_Id " 
				+ " inner join department as T3 on T1.dept_Id = T3.dept_Id " 
				+ " where T1.TRAINEE in (";
		StringBuilder sb = new StringBuilder(hsql);
		for (int i = 0; i < traineeIds.length; i++) {
			if(StringUtils.isNotEmpty(traineeIds[i])) {
				if(i != 0) {
					sb.append(",");
				}
				sb.append(traineeIds[i]);
			}
		}
		sb.append(")");
		sb.append(" and TIMESTAMP >= '" + beginDate + "'");
		sb.append(" and TIMESTAMP <= '" + endDate + "'");
		sb.append(" order by TIMESTAMP");
		List<IndividualAnalResultItem> list = new ArrayList<IndividualAnalResultItem>();
		Session session = HibernateSessionFactory.getSession();
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			Connection conn = session.connection();
			ps = conn.prepareStatement(sb.toString());
			rs = ps.executeQuery(sb.toString());
			while(rs.next()) {
				IndividualAnalResultItem item = new IndividualAnalResultItem();
				item.setTraineeId(rs.getInt(1));
				item.setTraineeName(rs.getString(2));
				item.setDate(rs.getString(3));
				item.setScore(rs.getFloat(4));
				list.add(item);
			}
		} catch (Exception e) {
			throw new DaoException(e);
		} finally {
			try {
				rs.close();
				ps.close();
			} catch (SQLException e) {
				throw new DaoException(e);
			}
			HibernateSessionFactory.closeSession();
		}
		return list;
	}

	@SuppressWarnings("unchecked")
	private List<QsCtMmoTestItem> parseResult(List result) {
		Iterator it = result.iterator();
		List<QsCtMmoTestItem> list = new ArrayList<QsCtMmoTestItem>();
		while (it.hasNext()) {
			Object[] o = (Object[]) it.next();
			QsCtMmoTest bean = (QsCtMmoTest) o[0];
			Person trainee = (Person) o[1];
			Person zdLeader = (Person) o[2];
			Person ddLeader = (Person) o[3];
			Department dept = (Department) o[4];
			QsCtMmoTestItem item = new QsCtMmoTestItem();
			item.setBean(bean);
			item.setTrainee(trainee);
			item.setZdLeader(zdLeader);
			item.setDdLeader(ddLeader);
			item.setDept(dept);
			list.add(item);
		}
		return list;
	}

	public int count(SearchBean searchBean) {
		return super.count(new Class[] { Person.class, Person.class,
				Person.class, Department.class }, QsCtMmoTest.class,
				JOIN_FIELDS, MASTER_FIELDS, searchBean);
	}
}
